﻿
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace System
{
    /// <summary>
    /// MD5扩展类
    /// </summary>
    public static class MD5Extensions
    {
        /// <summary>
        /// 获取字符串的MD5值
        /// </summary>
        /// <param name="text">字符串</param>
        /// <param name="encode">编码，缺省UTF8</param>
        /// <returns>MD5 值</returns>
        public static string ToMD5(this string text, Encoding encode = null)
        {
            if (encode == null) encode = Encoding.UTF8;
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] encryptedBytes = md5.ComputeHash(encode.GetBytes(text));
            return GetHashMD5(encryptedBytes);
        }
        /// <summary>
        /// 获取文件的MD5值
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string ToMD5File(this string path)
        {
            try
            {
                using (Stream file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    return file.ToMD5();
                }
            }
            catch (Exception e)
            {
                return e.ToString();
            }
        }
        /// <summary>
        /// 获取流的MD5值
        /// </summary>
        /// <param name="s">流</param>
        /// <returns>MD5值</returns>
        public static string ToMD5(this Stream stream)
        {
            byte[] hashbyte;
            using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
            {
                hashbyte = md5.ComputeHash(stream);
            }
            return GetHashMD5(hashbyte);
        }
        /// <summary>
        /// 获取字节数组的MD5值
        /// </summary>
        /// <param name="buffer">数组</param>
        /// <returns>MD5值</returns>
        public static string ToMD5(this byte[] buffer)
        {
            byte[] hashbyte;
            using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
            {
                hashbyte = md5.ComputeHash(buffer, 0, buffer.Length);
            }
            return GetHashMD5(hashbyte);
        }
        /// <summary>
        /// Hash值转换MD5值格式
        /// </summary>
        /// <param name="hashbyte">Hash值</param>
        /// <returns>MD5值</returns>
        private static string GetHashMD5(byte[] hashbyte)
        {
            string result = BitConverter.ToString(hashbyte);
            return result.Replace("-", "");
        }
    }
}
